load("js/cib_mobile/Barrett.js")
load("js/cib_mobile/BigInt.js")
load("js/cib_mobile/RSA.js")


var currency_type = "" ;
var   open_time = "";
var urls = {
    USER_AGENT:"Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Mobile Safari/537.36",
    ACCEPT:"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8"
}

var sdf = new SimpleDateFormat("yyyy-MM-dd");
var depitList = new ArrayList();


var v4_cib_mobile_debit_java_funcs = {
    checkProxyAvailable: function(){
        return true;
    },
    checkTargetWebsiteAvailable: function(){ return true },
    checkControlAvailable:function () {
        return true;
    },
    login:function(){
        var cardNo = getLoginParams(context)[0];//卡号
        var certNo = getLoginParams(context)[1];//身份证
        var passWord = context.get(Constants.LUA_TASK_TOKEN);

        //请求公钥
        var param = new HashMap();
        param.put("menu", "0100000020");
        var indexHtml = RequestUtil.post("https://3g.cib.com.cn/app/80820.html", param, getHttpPostTwo());
        storeDataToFile(context, indexHtml, "indexHtml.html");
        var first = indexHtml.indexOf("publicKey = ");
        var publicKeyStr = indexHtml.substring(first + "publicKey = ".length, first + "publicKey = ".length + 258);
        publicKeyStr = publicKeyStr.replaceAll("\"", "").replaceAll("\"", "");
        if(publicKeyStr.length() !== 256){
            publicKeyStr = "";
        }
        logger.info("任务【 {} 】公钥【 {} 】",context.get(LUA_TASK_KEY), publicKeyStr);

        //加密密码
        var passWordEncrypt = hsRSAEncrypt(passWord,publicKeyStr);
        logger.info("任务【 {} 】密文【 {} 】",context.get(LUA_TASK_KEY), passWordEncrypt);


        param.clear();
        //登录并返回结果
        var secendUrl = "https://3g.cib.com.cn/app/00002.html";
        param.put("flowsn", "402");
        param.put("hsm_pwd", passWordEncrypt);
        param.put("select_flag", "0");
        param.put("loginname", cardNo);
        param.put("req_zjhm", certNo);
        param.put("pwd", passWordEncrypt);
        var loginResultHtml = RequestUtil.post(secendUrl,param,getHttpPostTwo());
        storeDataToFile(context, loginResultHtml, "loginResult.html");

        var isLoginCorrectFunc = function(loginResultHtml) {
            if(StringUtils.isBlank(loginResultHtml)) {
                return false;
            }
            var doc = Jsoup.parse(loginResultHtml);

            if(equals(doc.select("#cvv2").attr("placeholder"), "卡片签名栏末三位")){
                return false

            }else if(equals("请按以下流程激活信用卡：",doc.select(".words").text())){
                return false
            }
            var checkText = doc.select("h2.mk-title").text()
            logger.info("任务【 {} 】待检查文本: '{}'", context.get(LUA_TASK_KEY), checkText)
            return StringUtils.isNotBlank(checkText) && checkText.contains("尊敬的")
        }

        var getLoginErrorMsgFunc = function(loginResultHtml) {
            if(StringUtils.isBlank(loginResultHtml)) {
                return "登录超时";
            }
            var doc = Jsoup.parse(loginResultHtml);

            var checkText = doc.select("#cvv2").attr("placeholder")
            logger.info("任务【 {} 】待检查文本: '{}'", context.get(LUA_TASK_KEY), checkText)

            var  activateCard = doc.select(".words").text();
            logger.info("任务【 {} 】激活的卡: '{}'", context.get(LUA_TASK_KEY), activateCard)

            if(equals(checkText, "请输入签名栏末三位")){
                return "请输入卡片签名栏末三位"
            }else if(equals("请按以下流程激活信用卡：",activateCard)){
                return "请按以下流程激活信用卡"
            }

            var errorMsg = doc.select("p.result-describe").text();
            logger.info("任务【 {} 】错误信息: {}", context.get(LUA_TASK_KEY), errorMsg)
            return errorMsg
        }

        assertTrueOrThrowException(loginResultHtml, isLoginCorrectFunc, getLoginErrorMsgFunc)
        logger.info("任务【 {} 】登录成功", context.get(LUA_TASK_KEY))
    },
    crawl:function(){
        var param = new HashMap();
        var creditCardAllData = new CreditCardAllData();

        //卡的数量
        var cardURL = "https://3g.cib.com.cn/app/80820.html";
        param.clear();
        param.put("menu", "0100000021");
        param.put("divtype", "");
        RequestUtil.post(cardURL,param,getHttpPostOne());
        param.clear();
        param.put("flowsn", "50");
        param.put("secmenu", "0200000316");
        var cardCountHtml = RequestUtil.post(cardURL,param,getHttpPostOne());
        if(cardCountHtml.contains("请使用理财卡登录后再继续操作")){
            throw  new BankException(BALO_22102_10, "登录方式错误");
        }
        storeDataToFile(context,cardCountHtml, "cardList.html");
        var cardCountDoc = Jsoup.parse(cardCountHtml);
        var counts = cardCountDoc.select(".m-card-wrap li");

        for(var cardNum = 1 ; cardNum <= counts.size(); cardNum ++){

            //基本信息
            parseBaseInfo(creditCardAllData,param,cardNum);

            var  creditCardTimeDeposits = new ArrayList();
            //存款
            creditCardAllData.setDeposits(creditCardTimeDeposits);
            var  billAllDatas =  new ArrayList();
            //存款信息
            creditCardAllData.setBills(billAllDatas);

            //账单流水
            billInfoDetail(creditCardAllData,param,cardNum);

            //定期
            saveDeposits(creditCardAllData,param,cardNum);
        }
        depitList.add(creditCardAllData);
        context.put(DEBIT_DATA, depitList);
    },
    exitLogin :function () {}
}


/**
 * 给pwd加密
 * @type {string}
 */
function hsRSAEncrypt(str,publicKey){
    if(publicKey=="") return str;
    setMaxDigits(130);
    var key = new RSAKeyPair("10001" , "" , publicKey);
    var enStr = encryptedString(key,str);
    return enStr;
}

/**
 * 定期
 * @throws IOException
 * @throws ClientProtocolException
 */
function saveDeposits( creditCardAllData, param, cardNum) {
    logger.info("===开始抓取定期=====");
    var  deposit = null;
    try {
        /**
         * 活期
         */
        var huoOne = "https://3g.cib.com.cn/app/80820.html";
        param.clear();
        param.put("menu", "0100000020");
        param.put("divtype", "");
        RequestUtil.post(huoOne,param,getHttpPostOne());
        var huoTwo = "https://3g.cib.com.cn/app/10020.html";
        param.clear();
        param.put("flowsn", "201");
        param.put("listcardno", "0");
        param.put("listno", "0");
        var huoTwoHtml = RequestUtil.post(huoTwo,param,getHttpPostOne());
        storeDataToFile(context,huoTwoHtml, cardNum + "_card_cunchu.html");

        var huoTwoDoc = Jsoup.parse(huoTwoHtml);
        var tables = huoTwoDoc.select("table");
        var balance = "";
        var deposit_date = "";
        var due_date ="";
        var deposit_type ="";
        for(var i = 0;i < tables.size()-1; i++){
            deposit = new CreditCardTimeDeposit();
            var text = huoTwoDoc.select("body > div.content > form > table:nth-child("+(4+i)+") > tbody > tr:nth-child(1) > td:nth-child(1)").text().trim();
            if(equals(text,"人民币活期存款")){
                balance = huoTwoDoc
                    .select("body > div.content > form > table:nth-child(4) > tbody > tr:nth-child(2) > td:nth-child(1)")
                    .text().replaceAll("账户余额：", "").replaceAll(",", "");
                var huoqiURL = "https://3g.cib.com.cn/app/10020.html";
                param.clear();
                param.put("flowsn", "250");
                param.put("mxlistno", "001");
                param.put("cardindex", "0");
                var huoqiBaseHtml = RequestUtil.post(huoqiURL,param,getHttpPostThree());
                storeDataToFile(context,huoqiBaseHtml, cardNum +"_card_cunchu_huoqi.html");
                var huoqiBaseDoc = Jsoup.parse(huoqiBaseHtml);
                // 定期类型
                deposit_type = huoqiBaseDoc
                    .select("body > div.content > div.product-introduce > div:nth-child(1) > div:nth-child(2) > span")
                    .text().trim();

                // 定期金额
                deposit.setBalance(new BigDecimal(balance));
                // 定期类型
                deposit.setDepositType(deposit_type);
                // 定期币种
                deposit.setCurrencyType("CNY");
                // 计息时间
                // deposit.setDepositDate(yyyy_MM_dd_PARSER.parse(!equals(deposit_date,"") ? deposit_date : null  ));
                // 到期时间
                // deposit.setDueDate(yyyy_MM_dd_PARSER.parse(due_date));
                // 存期
                deposit.setPeriod(null);
                // 存期单位
                deposit.setPeriodUnit("");

            }else if (equals(text,"人民币定期存款")){
                var depURL="https://3g.cib.com.cn/app/10000.html";
                param.clear();
                param.put("flowsn", "50");
                param.put("secmenu", "0300001030");
                RequestUtil.post(depURL,param,getHttpPostOne());
                var depDetailsURL ="https://3g.cib.com.cn/app/20021.html";
                param.clear();
                param.put("flowsn", "100");
                param.put("listno", "0");
                param.put("beginNo", "");
                var depDetailsHtml = RequestUtil.post(depDetailsURL,param,getHttpPostTwo());
                storeDataToFile(context,depDetailsHtml, cardNum + "_card_cunchu_dingqi.html");
                var depDetailsDoc = Jsoup.parse(depDetailsHtml);
                //定期类型
                deposit_type = depDetailsDoc.select("body > div.content > div.form-box.mat5 > ul > li:nth-child(2) > strong").text();
                //金额
                balance = depDetailsDoc.select("body > div.content > div.form-box.mat5 > ul > li:nth-child(3) > strong").text().replaceAll(",", "");
                //计息时间
                deposit_date = depDetailsDoc.select("body > div.content > div.form-box.mat5 > ul > li:nth-child(7) > strong").text().replaceAll("/", "-");
                //到期时间
                due_date = depDetailsDoc.select("body > div.content > div.form-box.mat5 > ul > li:nth-child(8) > strong").text().replaceAll("/", "-");
                //存期时间   三个月
                var period = depDetailsDoc.select("body > div.content > div.form-box.mat5 > ul > li:nth-child(5) > strong").text();
                //利率
                if (equals(period,"三个月")) {
                    deposit.setInterest(new BigDecimal("0.014"));
                } else if (equals(period,"六个月")) {
                    deposit.setInterest(new BigDecimal("0.0165"));
                } else if (equals(period,"一年")) {
                    deposit.setInterest(new BigDecimal("0.0195"));
                } else if (equals(period,"二年")) {
                    deposit.setInterest(new BigDecimal("0.027"));
                } else if (equals(period,"三年")) {
                    deposit.setInterest(new BigDecimal("0.032"));
                } else if (equals(period,"五年")) {
                    deposit.setInterest(new BigDecimal("0.032"));
                }

                // 存期单位
                var period_unit = period.contains("月") ? "MONTH": "YEAR";

                period = period.substring(0, 1);
                if(equals(period,"一")){
                    period ="1";
                }else if(equals(period,"二")){
                    period ="2";
                }else if(equals(period,"三")){
                    period ="3";
                }else if(equals(period,"五")){
                    period ="5";
                }else if(equals(period,"六")){
                    period ="6";
                }
                //定期金额
                deposit.setBalance(new BigDecimal(balance));
                //定期类型
                deposit.setDepositType(deposit_type);
                //定期币种
                deposit.setCurrencyType("CNY");
                //计息时间
                deposit.setDepositDate(yyyy_MM_dd_PARSER.parse(deposit_date));
                //到期时间
                deposit.setDueDate(yyyy_MM_dd_PARSER.parse(due_date));
                //存期
                deposit.setPeriod(Integer.parseInt(period));
                //存期单位
                deposit.setPeriodUnit(period_unit);
            }
            //将CreditCardTimeDeposit添加到集合中
            creditCardAllData.getDeposits().add(deposit);
        }
    } catch (e) {
        logger.error("{}，兴业借记卡存储抓取异常:{}",context.get(LUA_TASK_KEY),e);
        statCaughtException(context, e);
    }
}

/**
 * 账户信息
 * @return
 * @throws Exception
 */
function parseBaseInfo( creditCardAllData, param, cardNum){
    logger.info("=====开始抓取基本信息======");
    try {
        //卡id
        creditCardAllData.setCardId(UUID.randomUUID().toString());
        //卡类型
        creditCardAllData.setCardType("借记卡");
        //卡名字
        creditCardAllData.setBankName("兴业银行");
        creditCardAllData.setCashBalance(null);
        creditCardAllData.setCashLimit(null);
        creditCardAllData.setCreditLimit(null);
        /**
         * 开户行
         */
        var openBankURL = "https://3g.cib.com.cn/app/20901.html" ;
        param.clear();
        param.put("flowsn", "0");
        param.put("listcardno", "0");
        param.put("listno", "0");
        var openBankHtml =RequestUtil.post(openBankURL,param,getHttpPostTwo());
        storeDataToFile(context,openBankHtml, cardNum + "_openBankXml.html");
        if(openBankHtml.contains("该业务仅支持借记卡办理，请使用借记卡登录后继续办理。")){
            throw  new BankException(BALO_99604_15, errorMsgMap.get(BALO_99604_15));
        }
        var openBankDoc = Jsoup.parse(openBankHtml);
        var openBank = openBankDoc.select("body > div.content > div.purchase-info > ul > li.top-inline.clearfix > span").text().trim().replaceAll("\\u00A0", "");
        var fullcardNum = openBankDoc.select("body > div.content > form > div.card-info.card_bg > div.card-account > em:nth-child(2)").text().trim().replaceAll("\\s*", "").replaceAll("\\u00A0", "");
        var name = openBankDoc.select("body > div.content > form > div.card-info.card_bg > div:nth-child(2) > span.fl.mat5").text().trim().replaceAll("\\u00A0", "");;
        //完整卡号
        creditCardAllData.setFullCardNum(fullcardNum);
        //卡号后四位
        creditCardAllData.setCardNum(fullcardNum.substring((fullcardNum.length()-4), (fullcardNum.length())));
        //开户行
        creditCardAllData.setOpenBank(openBank);
        //持卡人
        creditCardAllData.setNameOnCard(name);

        var baseURL="https://3g.cib.com.cn/app/80820.html";
        param.clear();
        param.put("flowsn", "50");
        param.put("secmenu", "0200000300");
        var baseHtml = RequestUtil.post(baseURL,param,getHttpPostTwo());
        storeDataToFile(context,baseHtml, cardNum + "_card.html");
        var baseDoc = Jsoup.parse(baseHtml);
        //币种
        currency_type = CreditResultUtil.convertCurr(baseDoc.select("body > div.content > form:nth-child(1) > div > div > p").text()
            .replaceAll("活期可用余额", ""));
        var huoTwoUrl = "https://3g.cib.com.cn/app/10020.html";
        param.clear();
        param.put("flowsn", "201");
        param.put("listcardno", "0");
        param.put("listno", "0");
        var huoTwoHtml = RequestUtil.post(huoTwoUrl,param,getHttpPostOne());
        storeDataToFile(context,huoTwoHtml, cardNum + "_card_huotwo.html");

        var huoTwoDoc = Jsoup.parse(huoTwoHtml);
        var tables = huoTwoDoc.select("table");
        var balanceSum = 0.0;
        for (var i = 0; i < tables.size() - 1; i++) {
            var text = huoTwoDoc.select("body > div.content > form > table:nth-child(" + (4 + i)
                + ") > tbody > tr:nth-child(1) > td:nth-child(1)").text().trim();
            if (equals(text,"人民币活期存款")) {
                var 	balance= huoTwoDoc.select("body > div.content > form > table:nth-child(4) > tbody > tr:nth-child(2) > td:nth-child(1)").text().replaceAll("账户余额：", "").replaceAll(",", "");
                balanceSum = balanceSum + Double.parseDouble(balance);
                var huoqiURL = "https://3g.cib.com.cn/app/10020.html";
                param.clear();
                param.put("flowsn", "250");
                param.put("mxlistno", "001");
                param.put("cardindex", "0");
                var huoqiBaseHtml =RequestUtil.post(huoqiURL,param,getHttpPostThree());
                storeDataToFile(context,huoqiBaseHtml, cardNum + "_card_kaihu.html");
                var huoqiBaseDoc = Jsoup.parse(huoqiBaseHtml);
                //开户时间
                open_time = huoqiBaseDoc.select("body > div.content > div.product-introduce > div:nth-child(4) > div:nth-child(1) > span").text().trim().replaceAll("/", "-");
                // 开户时间
                creditCardAllData.setOpenTime(yyyy_MM_dd_PARSER.parse(open_time));
            }else if(equals(text,"人民币定期存款")){
                var 	balance= huoTwoDoc.select("body > div.content > form > table:nth-child(5) > tbody > tr:nth-child(1) > td:nth-child(2)").text().trim().replaceAll(",", "");
                balanceSum = balanceSum + Double.parseDouble(balance);
            }
        }
        creditCardAllData.setBalance(new BigDecimal(String.valueOf(balanceSum)));
    } catch (e) {
        logger.error("{}，兴业借记卡抓取异常:{}",context.get(Constants.LUA_TASK_KEY),e);
        statCaughtException(context, e);
    }
}

/**
 * 获取6个月的第一天  格式:2017-01-01
 * @return
 * @throws Exception
 */

function  getMonthFirstDay(){
    var lst = new ArrayList();

    var calendar = new GregorianCalendar();
    var dfdate = new SimpleDateFormat("yyyy-MM-dd");

    for (var i = 0; i < 12; i++) {

        calendar.setTime(new Date());
        calendar.add(Calendar.MONTH, -1 * i);

        var gcLast = Calendar.getInstance();
        gcLast.setTime(calendar.getTime());
        gcLast.set(Calendar.DAY_OF_MONTH, 1);
        lst.add(dfdate.format(gcLast.getTime()));
    }
    return lst;
}

/**
 * 获取六个月的最后一天,当月就返回到今天
 */
function getMonthLastDay(){
    var lst = new ArrayList();

    var calendar = new GregorianCalendar();

    var dfdate = new SimpleDateFormat("yyyy-MM-dd");

    for (var i = -1; i < 11; i++) {

        calendar.setTime(new Date());
        calendar.add(Calendar.MONTH, -1 * i);

        var gcLast =  Calendar.getInstance();
        gcLast.setTime(calendar.getTime());
        gcLast.set(Calendar.DATE, 1);
        gcLast.add(Calendar.DATE, -1);
        if (gcLast.getTime().after(new Date())) {
            lst.add(dfdate.format(new Date()));
        } else {
            lst.add(dfdate.format(gcLast.getTime()));
        }
    }
    return lst;
}

/**
 * 六个月的账单详情
 * @return
 * @throws IOException
 * @throws ClientProtocolException
 * @throws Exception
 */
function billInfoDetail( creditCardAllData, param, cardNum) {
    var monthFirstDay = getMonthFirstDay();
    var monthLastDay = getMonthLastDay();
    for(var i = 0 ; i < 12; i ++){

         if(!equals(open_time,"")){
             if (sdf.parse(open_time).after(sdf.parse(monthFirstDay.get(i)))
                 && sdf.parse(open_time).after(sdf.parse(monthLastDay.get(i)))) {
                 break;
             }
         }

        //每月的第一天
        var firstDay = monthFirstDay.get(i);
        //每月的最后一天
        var lastDay = monthLastDay.get(i);

        var billAllData = new BillAllData();
        billAllData.setBillId(UUID.randomUUID().toString());
        billAllData.setBillType("");
        billAllData.setBankName("兴业银行");
        billAllData.setBillMonth(firstDay.substring(0, 7));//格式:yyyy-MM   2017-06
        billAllData.setBillDate(yyyy_MM_dd_PARSER.parse(firstDay));
        billAllData.setNewBalance(null);
        billAllData.setUsdNewBalance(null);
        billAllData.setMinPayment(null);
        billAllData.setUsdMinPayment(null);
        billAllData.setLastBalance(null);
        billAllData.setUsdLastBalance(null);
        billAllData.setLastPayment(null);
        billAllData.setUsdLastPayment(null);
        billAllData.setNewCharges(null);
        billAllData.setUsdNewCharges(null);
        billAllData.setInterest(null);
        billAllData.setUsdInterest(null);
        billAllData.setUsdInterest(null);
        billAllData.setCreditLimit(null);
        billAllData.setUsdCreditLimit(null);
        billAllData.setCashLimit(null);
        billAllData.setUsdCashLimit(null);

        var expenses = new ArrayList();
        //账单详情
        billAllData.setShoppingSheets(expenses);
        firstDay = firstDay.replaceAll("-", "");
        lastDay = lastDay.replaceAll("-", "");
        saveBillsDetail(creditCardAllData, billAllData, firstDay, lastDay, param,cardNum,i);
        creditCardAllData.getBills().add(billAllData);
    }
}

/**
 * 账单详情
 * @param creditCardAllData
 * @param billAllData
 * @param firstDay
 * @param lastDay
 * @throws IOException
 * @throws ClientProtocolException
 */
function saveBillsDetail( creditCardAllData,  billAllData, firstDay, lastDay, param, cardNum, q)  {
    logger.info("开始抓取{}账单",firstDay);
    try {
        var baseURL="https://3g.cib.com.cn/app/80820.html";
        param.clear();
        param.put("flowsn", "50");
        param.put("secmenu", "0200000300");
        RequestUtil.post(baseURL,param,getHttpPostOne());
        var billsDetailTwoURL = "https://3g.cib.com.cn/app/10040.html";
        param.clear();
        param.put("flowsn", "4");
        param.put("listcardno", "0");
        param.put("listno", "0");
        RequestUtil.post(billsDetailTwoURL,param,getHttpPostFour());
        param.clear();
        param.put("flowsn", "15");
        param.put("xxh", "001");
        param.put("begindate", firstDay);
        param.put("enddate",lastDay);
        param.put("qrytype", "1");
        var billsDetailThreeHtml = RequestUtil.post(billsDetailTwoURL,param,getHttpPostFour());
        storeDataToFile(context,billsDetailThreeHtml, cardNum + "_bill_" + firstDay + ".html");
        /**
         * 判断有没有
         */
        if(billsDetailThreeHtml.contains("对不起，找不到符合条件的交易明细。")){
            return;
        }

        var billsDetailThreeDoc = Jsoup.parse(billsDetailThreeHtml);

        var  sumPage = billsDetailThreeDoc.select("body > div.content > div.mat10 > form:nth-child(3) > p > span > em").text().replaceAll("\\[", "").replaceAll("\\]", "");
        var sumP = sumPage.split("/");

        var billsDetailThreeForm = billsDetailThreeDoc.select("body > div.content > div.mat10 > form:nth-child(1)");
        var children = billsDetailThreeForm.get(0).children();
        var order = 0;
        for(var i = 2 ; i < children.size();i++){
            var expense = new Expense();
            param.clear();
            param.put("flowsn", "200");
            param.put("listno", (i-2)+"");
            var billsDetailFour = RequestUtil.post(billsDetailTwoURL,param,getHttpPostOne());
            storeDataToFile(context,billsDetailFour, cardNum +"_bill_shopping_sheets_"+ (i-1)+".html");
            var billsDetailFourDoc = Jsoup.parse(billsDetailFour);

            //记账时间
            var post_date = billsDetailFourDoc.select("body > div.content > div.product-introduce > div:nth-child(3) > div:nth-child(2) > span").text().trim().replaceAll("/", "-");

            //交易时间
            var trans_date = billsDetailFourDoc.select("body > div.content > div.product-introduce > div:nth-child(3) > div:nth-child(1) > span").text().trim().replaceAll("/", "-");

            //交易金额
            var amount_moneyText = billsDetailFourDoc.select("body > div.content > div.product-introduce > div:nth-child(1) > div > p").text().trim();
            var amount_money = billsDetailFourDoc.select("body > div.content > div.product-introduce > div:nth-child(1) > div > span").text().trim().replaceAll(",", "");


            //账户余额
            var balance = billsDetailFourDoc.select("body > div.content > div.product-introduce > div:nth-child(2) > div:nth-child(2) > span").text().trim().replaceAll(",","");

            //对方信息   包括对方持卡人 和对方卡号      (步延伟5218991349688785)
            var  name_on_opposite_card = billsDetailFourDoc.select("body > div.content > div.product-introduce > div:nth-child(4) > div > span").text().trim();
            var p = Pattern.compile("([\u4e00-\u9fa5]+)");
            var m = p.matcher(name_on_opposite_card);
            var sb = new StringBuffer("");
            while (m.find()) {
                sb.append(URLDecoder.decode(m.group(1),"UTF-8"));
            }

            //对方卡号
            var  opposite_card_no = billsDetailFourDoc.select("body > div.content > div.product-introduce > div:nth-child(4) > div > span > span").text().trim();

            //对方银行
            var  opposite_bank = billsDetailFourDoc.select("body > div.content > div.product-introduce > div:nth-child(5) > div > span").text().trim();

            //交易摘要
            var  description = billsDetailFourDoc.select("body > div.content > div.product-introduce > div:nth-child(2) > div:nth-child(1) > span").text().trim();
            if(amount_moneyText.contains("收入")){
                amount_money = "-" + amount_money ;
                // 消费类型
                expense.setCategory(CategoryUtil.getDebitCategory(description,  amount_money));
            }else if (amount_moneyText.contains("支出")){
                amount_money = "+" + amount_money ;
                // 消费类型
                expense.setCategory(CategoryUtil.getDebitCategory(description, amount_money));
            }
            //备注
            var remark = billsDetailFourDoc.select(" body > div.content > div.product-introduce > div:nth-child(6) > div > span").text().trim();

            // 消费id
            expense.setId(UUID.randomUUID().toString());
            // 卡号末四位
            expense.setCardNum(creditCardAllData.getCardNum());
            // 记账日期
            expense.setPostDate(yyyy_MM_dd_PARSER.parse(post_date));

            // 排序
            expense.setOrderIndex(++order);
            // 交易时间
            expense.setTransDate(yyyy_MM_dd_HH_mm_ss_PARSER.parse(trans_date));
            // 币种
            expense.setCurrencyType("CNY");
            // 消费金额
            expense.setAmountMoney(new BigDecimal(amount_money));
            // 余额
            expense.setBalance(new BigDecimal(balance));
            // 交易地点
            expense.setTransAddr("");
            // 交易方式
            expense.setTransMethod("");
            // 交易通道
            expense.setTransChannel("");
            // 描述
            expense.setDescription(description);
            // 备注
            expense.setRemark(remark);
            // 对方卡号
            expense.setOppositeCardNo(opposite_card_no);
            // 对方银行
            expense.setOppositeBank(opposite_bank);
            // 对方户名
            expense.setNameOnOppositeCard(sb.toString());

            billAllData.getShoppingSheets().add(expense);

        }


        if(sumPage !== ""){

            //分页
            for(var currentPage = 2 ; currentPage <=Integer.parseInt(sumP[1]); currentPage ++){
                param.clear();
                param.put("beginNo",  (currentPage - 1) + "1");
                param.put("flowsn", "75");
                var billsDetailsNextPageHtml = RequestUtil.post(billsDetailTwoURL,param,getHttpPostFour());
                storeDataToFile(context,billsDetailsNextPageHtml, cardNum + "_bill_shopping_sheets_"+ currentPage+ ".html");
                var billsDetailsNextPageDoc = Jsoup.parse(billsDetailsNextPageHtml);
                var billsDetailsNextPage = billsDetailsNextPageDoc.select("body > div.content > div.mat10 > form:nth-child(1)");
                var childs = billsDetailsNextPage.get(0).children();
//			int j = 10;
                var sum = 10;
                for(var i = 2 ; i < childs.size();i++){

                    var expense = new Expense();
                    param.clear();
                    param.put("flowsn", "200");
                    param.put("listno", (currentPage-1)+""+(i-2));
                    var billsDetailFour = RequestUtil.post(billsDetailTwoURL,param,getHttpPostOne());
                    storeDataToFile(context,billsDetailFour, cardNum + "_bill_shopping_sheets_" + ((currentPage-1)+""+(i-1)) +".html");
                    var billsDetailFourDoc = Jsoup.parse(billsDetailFour);
                    //记账时间
                    var post_date = billsDetailFourDoc.select("body > div.content > div.product-introduce > div:nth-child(3) > div:nth-child(2) > span").text().trim().replaceAll("/", "-");
                    //交易时间
                    var trans_date = billsDetailFourDoc.select("body > div.content > div.product-introduce > div:nth-child(3) > div:nth-child(1) > span").text().trim().replaceAll("/", "-");

                    //交易摘要
                    var  description = billsDetailFourDoc.select("body > div.content > div.product-introduce > div:nth-child(2) > div:nth-child(1) > span").text().trim();

                    //交易金额
                    var amount_moneyText = billsDetailFourDoc.select("body > div.content > div.product-introduce > div:nth-child(1) > div > p").text().trim();
                    var amount_money = billsDetailFourDoc.select("body > div.content > div.product-introduce > div:nth-child(1) > div > span").text().trim().replaceAll(",", "");
                    if(amount_moneyText.contains("收入")){
                        amount_money = "-" + amount_money ;
                        // 消费类型
                        expense.setCategory(CategoryUtil.getDebitCategory(description,  amount_money));
                    }else if (amount_moneyText.contains("支出")){
                        amount_money = "+" + amount_money ;
                        // 消费类型
                        expense.setCategory(CategoryUtil.getDebitCategory(description,  amount_money));
                    }

                    //账户余额
                    var balance = billsDetailFourDoc.select("body > div.content > div.product-introduce > div:nth-child(2) > div:nth-child(2) > span").text().trim().replaceAll(",", "");
                    //对方信息   包括对方持卡人 和对方卡号      (步延伟5218991349688785)
                    var  name_on_opposite_card = billsDetailFourDoc.select("body > div.content > div.product-introduce > div:nth-child(4) > div > span").text().trim();
                    var p = Pattern.compile("([\u4e00-\u9fa5]+)");
                    var m = p.matcher(name_on_opposite_card);
                    var sb = new StringBuffer("");
                    var str = "";
                    while (m.find()) {
                        sb.append(URLDecoder.decode(m.group(1), "UTF-8"));
//		        	str+=m.group(1);
                    }

                    //对方卡号
                    var  opposite_card_no = billsDetailFourDoc.select("body > div.content > div.product-introduce > div:nth-child(4) > div > span > span").text().trim();

                    //对方银行
                    var  opposite_bank = billsDetailFourDoc.select("body > div.content > div.product-introduce > div:nth-child(5) > div > span").text().trim();

                    //备注
                    var remark = billsDetailFourDoc.select("body > div.content > div.product-introduce > div:nth-child(6) > div > span").text().trim();

                    // 消费id
                    expense.setId(UUID.randomUUID().toString());
                    // 卡号末四位
                    expense.setCardNum(creditCardAllData.getCardNum());
                    // 记账日期
                    expense.setPostDate(yyyy_MM_dd_PARSER.parse(post_date));
                    // 排序
                    expense.setOrderIndex(++order);
                    // 交易时间
                    expense.setTransDate(yyyy_MM_dd_HH_mm_ss_PARSER.parse(trans_date));
                    // 币种
                    expense.setCurrencyType("CNY");
                    // 消费金额
                    expense.setAmountMoney(new BigDecimal(amount_money));
                    // 余额
                    expense.setBalance(new BigDecimal(balance));
                    // 交易地点
                    expense.setTransAddr("");
                    // 交易方式
                    expense.setTransMethod("");
                    // 交易通道
                    expense.setTransChannel("");
                    // 描述
                    expense.setDescription(description);
                    // 备注
                    expense.setRemark(remark);
                    // 对方卡号
                    expense.setOppositeCardNo(opposite_card_no);
                    // 对方银行
                    expense.setOppositeBank(opposite_bank);
                    // 对方户名
                    expense.setNameOnOppositeCard(sb.toString());
//				expense.setNameOnOppositeCard(new String (str.getBytes(),"UTF-8"));

                    billAllData.getShoppingSheets().add(expense);

                }
            }
        }
    } catch (e) {
        logger.error("{}，兴业借记卡{}月账单抓取异常:{}",context.get(LUA_TASK_KEY),firstDay,e);
        statCaughtException(context, e);
    }
}
/*
 * 返回Referer值带有80820的httpost
 * @param
 * @return
 */
function  getHttpPostOne(){
    var header = new HashMap();
    header.put("Referer", "https://3g.cib.com.cn/app/80820.html");
    header.put("User-Agent", urls.USER_AGENT);
    header.put("Origin", "https://3g.cib.com.cn");
    header.put("Host", "3g.cib.com.cn");
    header.put("Accept", urls.ACCEPT);
    return header;
}

/**
 * 返回referer带有00002的httppost
 * @param
 * @return
 */
function   getHttpPostTwo(){
    var header = new HashMap();
    header.put("Referer", "https://3g.cib.com.cn/app/00002.html");
    header.put("User-Agent", urls.USER_AGENT);
    header.put("Origin", "https://3g.cib.com.cn");
    header.put("Host", "3g.cib.com.cn");
    header.put("Accept", urls.ACCEPT);
    return header;
}

/**
 * 返回referer带有10020的httppost
 * @param
 * @return
 */
function   getHttpPostThree(){

    var header = new HashMap();
    header.put("Referer", "https://3g.cib.com.cn/app/10020.html");
    header.put("User-Agent", urls.USER_AGENT);
    header.put("Origin", "https://3g.cib.com.cn");
    header.put("Host", "3g.cib.com.cn");
    header.put("Accept", urls.ACCEPT);
    return header;
}

/**
 * 返回referer带有10040的httppost
 * @param
 * @return
 */
function   getHttpPostFour(){

    var  header = new HashMap();
    header.put("Referer", "https://3g.cib.com.cn/app/10040.html");
    header.put("User-Agent", urls.USER_AGENT);
    header.put("Origin", "https://3g.cib.com.cn");
    header.put("Host", "3g.cib.com.cn");
    header.put("Accept", urls.ACCEPT);
    return header;
}